package com.seocoo.worker;

import android.app.Activity;
import android.app.Application;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.seocoo.worker.base.city.ReqCityList;
import com.seocoo.worker.base.entity.ECity;
import com.seocoo.worker.base.http.BaseRsp;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.HandleException;
import com.sfh.lib.ICrashReport;
import com.sfh.lib.utils.ThreadTaskUtils;
import com.tencent.bugly.crashreport.CrashReport;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import cn.jpush.android.api.JPushInterface;
import me.jessyan.autosize.AutoSize;
import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.onAdaptListener;
import me.jessyan.autosize.utils.AutoSizeLog;

import static com.zaaach.citypicker.db.DBConfig.COLUMN_C_CODE;
import static com.zaaach.citypicker.db.DBConfig.COLUMN_C_NAME;
import static com.zaaach.citypicker.db.DBConfig.COLUMN_C_PINYIN;
import static com.zaaach.citypicker.db.DBConfig.COLUMN_C_PROVINCE;
import static com.zaaach.citypicker.db.DBConfig.LATEST_DB_NAME;
import static com.zaaach.citypicker.db.DBConfig.TABLE_NAME;

/**
 * 功能描述:
 *
 * @author
 * @date 2020/2/16
 */
public class WorkerAppContent extends Application {

    @Override
    public void onCreate() {

        super.onCreate();
        CrashReport.initCrashReport(getApplicationContext(), "3a4ab9bbd1", true);
        HandleException.setErrorHandler(new ICrashReport() {
            @Override
            public HandleException accept(Throwable t) {
                CrashReport.postCatchedException(t);
                return null;
            }
        });
        new AppCacheManager.Builder(this).setCachePath("doorsworker").build();
        /**
         * 以下是 AndroidAutoSize 可以自定义的参数, {@link AutoSizeConfig} 的每个方法的注释都写的很详细
         * 使用前请一定记得跳进源码，查看方法的注释, 下面的注释只是简单描述!!!
         */
        AutoSizeConfig.getInstance()

                //是否屏蔽系统字体大小对 AndroidAutoSize 的影响, 如果为 true, App 内的字体的大小将不会跟随系统设置中字体大小的改变
                //如果为 false, 则会跟随系统设置中字体大小的改变, 默认为 false
                .setExcludeFontScale(true)

                //屏幕适配监听器
                .setOnAdaptListener(new onAdaptListener() {
                    @Override
                    public void onAdaptBefore(Object target, Activity activity) {
                        //使用以下代码, 可以解决横竖屏切换时的屏幕适配问题
                        //使用以下代码, 可支持 Android 的分屏或缩放模式, 但前提是在分屏或缩放模式下当用户改变您 App 的窗口大小时
                        //系统会重绘当前的页面, 经测试在某些机型, 某些情况下系统不会重绘当前页面, ScreenUtils.getScreenSize(activity) 的参数一定要不要传
                        AutoSizeLog.d(String.format(Locale.ENGLISH, "%s onAdaptBefore!", target.getClass().getName()));
                    }

                    @Override
                    public void onAdaptAfter(Object target, Activity activity) {
                        AutoSizeLog.d(String.format(Locale.ENGLISH, "%s onAdaptAfter!", target.getClass().getName()));
                    }
                }).setUseDeviceSize(true);

        ThreadTaskUtils.execute(new Runnable() {
            @Override
            public void run() {

                try {

                    BaseRsp<List<ECity>> listBaseRsp = new ReqCityList().call();
                    if (listBaseRsp != null && listBaseRsp.success()) {

                        new DBManager(WorkerAppContent.this);

                        String db_path = File.separator + "data"
                                + Environment.getDataDirectory().getAbsolutePath() + File.separator
                                + getPackageName() + File.separator + "databases" + File.separator;
                        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(db_path + LATEST_DB_NAME, null);

                        try {
                            db.beginTransaction();
                            db.delete(TABLE_NAME, null, null);

                            for (ECity city : listBaseRsp.getData()) {
                                ContentValues values = new ContentValues();
                                values.put(COLUMN_C_NAME, city.fullName);
                                values.put(COLUMN_C_PROVINCE, "");
                                values.put(COLUMN_C_PINYIN, city.pinyin);
                                values.put(COLUMN_C_CODE, city.cityCode);
                                db.insert(TABLE_NAME, null, values);
                            }

                            db.setTransactionSuccessful();
                        } finally {
                            db.endTransaction();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    public void onExit() {
        AppCacheManager.getPersistListener().clear();
        // 打开应用首个打开界面
        JPushInterface.deleteAlias(this, 10001);
        Intent i = this.getPackageManager().getLaunchIntentForPackage(
                this.getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(i);
    }
}
